import express from 'express';
var router = express.Router();
import crypto from 'crypto'

import getToken from './getAccessToken.js'
import getOauth from './getOauth2Token.js'
import getSignature from './getSignature.js'
import login from './loginByWx.js';
import {addSql, getResult} from '../../util/operateSql.js'
import {generateToken,parseToken} from '../../util/common.js'
import cache from '../../cache.js';
import sendMessage from './sendMessage.js'
import subscribe from './subscribe.js'
import _ from 'lodash';

router.use('/',sendMessage)
router.use('/',subscribe)

const USERTABLE = 'activity_master.users'
const TABLE2 = 'activity_master.t_orgnization'

function sha1(str) {
  let md5sum = crypto.createHash("sha1")
  md5sum.update(str)
  str = md5sum.digest("hex")
  return str
}


// 是否存在微信用户
export function isExistCUser(openid) {
  return new Promise((resolve, reject) => {
    const sql = `select * from ${TABLE2} where openid = '${openid}'`
    getResult(sql).then((result) => {
        resolve(result[0])
    }).finally(err => {
      reject(err)
    })
  })
}

// 微信登录
router.post('/login', async (req, res, next) => {
  try {
    const  { jscode = '', avatar='',nickname='' } = req.body
    const { user } = req
    const {openid} = await login(jscode)
    if(!openid) {
      res.json(req.app.locals.error('无效的js_code'))
      next()
    }
    const hasExistUser = await isExistCUser(openid)
    const token = generateToken(openid)
    if (hasExistUser) {
      cache.setCache('token',`${token}`,{openid},1000*3600*2)
      _.omit(hasExistUser,'openid')
      res.json(req.app.locals.success({token,user:hasExistUser}))
    } else {
      const sql = addSql(TABLE2,{openid:openid,avatar,nickname})
      getResult(sql).then(() => {
        cache.setCache('token',`${token}`,{openid},1000*3600*2)
        res.json(req.app.locals.success({token,user: {avatar, nickname}}))
      })
    }

  } catch (error) {
    
    
    res.send(req.app.locals.error(error))
  }
})


router.get('/authorize', (req, res, next) => {
  let signature = req.query.signature
  let timestamp = req.query.timestamp
  let nonce = req.query.nonce
  let echostr = req.query.echostr

  let origin = [nonce, timestamp, 'weixin']
  origin.sort()

  let cryptStr = sha1(origin.join(''))
  if (signature == cryptStr) {
    res.send(echostr)
  } else {
    res.json('false')
  }
})

router.post('/authorize', (req, res, next) => {
  let signature = req.query.signature
  let timestamp = req.query.timestamp
  let nonce = req.query.nonce
  let echostr = req.query.echostr

  let origin = [nonce, timestamp, 'weixin']
  origin.sort()

  let cryptStr = sha1(origin.join(''))
  
  
  if (signature == cryptStr) {
    res.send(echostr)
  } else {
    res.json('false')
  }
})


router.get('/getToken', async (req, res, next) => {
  const params = req.query
  getToken(params).then((result) => {
    res.send(result)
  }).catch((err) => {
    
    res.send(err)
  });
})

router.get('/getOauth', async(req,res,next) => {
  const params = req.query
  getOauth(params).then((result) => {
    res.send(result)
  }).catch((err) => {
    res.send(err)
  });
})


/**
 * 
 * @param {String} accessToken access_token 
 * @param {String} url H5的链接
 * @returns 
 */
router.get('/getSignature', async (req, res, next) => {
  const params = req.query
  
  getSignature(params).then((result) => {
    
    res.send(result)
  }).catch((err) => {
    
    res.send(err)
  });
})



export default router